package com.food.foodapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.foodapi.instans.Result;
import com.food.foodapi.mapper.ArticleMapper;
import com.food.foodapi.mapper.TypeMapper;
import com.food.foodapi.model.entity.Article;
import com.food.foodapi.model.entity.Type;
import com.food.foodapi.model.result.TypeResult;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 92110
 */
@RestController
@RequestMapping("/type")
public class TypeController {
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private ArticleMapper articleMapper;

    @GetMapping("/list")
    public Result<List<Type>> list() {
        return Result.success(typeMapper.selectList(null));
    }

    @GetMapping("/list/count")
    public Result<List<TypeResult>> countList() {
        List<TypeResult> list = new ArrayList<>();
        List<Type> types = typeMapper.selectList(null);
        types.forEach(type -> {
            TypeResult result = new TypeResult();
            result.setId(type.getId());
            result.setName(type.getName());
            QueryWrapper<Article> eq = new QueryWrapper<Article>().eq("type", type.getId());
            Long count = articleMapper.selectCount(eq);
            result.setCount(Math.toIntExact(count));
            Article article = articleMapper.selectOne(new QueryWrapper<Article>()
                    .eq("type", type.getId()).orderByDesc("create_time").last("limit 1"));
            if (article != null) {
                result.setLastTime(article.getCreateTime());
            } else {
                result.setLastTime("当前模块还没有数据！");
            }

            list.add(result);
        });
        return Result.success(list);
    }
}
